﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Channels;
using System.Text;
using System.Threading.Tasks;

namespace ebMS3dotnet.Core
{
    public sealed class ebMS3BindingElement : BindingElement
    {
        public override BindingElement Clone()
        {
            return new ebMS3BindingElement();
        }

        public override T GetProperty<T>(BindingContext context)
        {
            return context.GetInnerProperty<T>();
        }

        public override bool CanBuildChannelFactory<TChannel>(BindingContext context)
        {
            if (context == null)
                throw new ArgumentNullException("context");

            if (typeof(TChannel) == typeof(IRequestChannel))
                return context.CanBuildInnerChannelFactory<TChannel>();

            return false;
        }

        public override IChannelFactory<TChannel> BuildChannelFactory<TChannel>(BindingContext context)
        {
            if (context == null)
                throw new ArgumentNullException("context");

            if (!CanBuildChannelFactory<TChannel>(context))
                throw new InvalidOperationException("Unsupported channel type");

            ebMS3PackagingChannelFactory<TChannel> factory = new ebMS3PackagingChannelFactory<TChannel>(context);
            return factory;
        }

        public override bool CanBuildChannelListener<TChannel>(BindingContext context)
        {
            if (context == null)
                throw new ArgumentNullException("context");

            if (typeof(TChannel) == typeof(IReplyChannel))
                return base.CanBuildChannelListener<TChannel>(context);

            return false;
        }

        public override IChannelListener<TChannel> BuildChannelListener<TChannel>(BindingContext context)
        {
            if (context == null)
                throw new ArgumentNullException("context");

            if(!CanBuildChannelListener<TChannel>(context))
                throw new InvalidOperationException("Unsupported channel type");

            ebMS3PackagingChannelListener<TChannel> listener = new ebMS3PackagingChannelListener<TChannel>(context);
            return listener;
        }
    }
}
